package javase.ch02.sync;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Desc TODO
 * @Author chenmin
 * @Date 2025/10/30
 *
 * Lock锁  悲观锁  接口
 * java.util.concurrent.locks.Lock  接口
 * java.util.concurrent.locks.ReentrantLock  实现类  可重入锁  非公平锁
 *
 * 1.构造方法
 * public ReentrantLock()
 * public ReentrantLock(boolean fair)
 *
 * 2.常用API方法
 * public void lock()   获取锁
 * public void unlock() 释放锁,一定要在finally中完成释放锁的动作，无论是否发生异常一定会释放锁
 * public boolean tryLock()  尝试获取锁,返回true代表获取到锁，返回false则代表未获取锁
 * public boolean tryLock(long timeout, TimeUnit unit)  指定的时间内,尝试获取锁
 *
 * 3.注意
 * 无论是否正常执行任务，最后释放锁资源
 */
public class LockDemo {

    //创建锁对象 可重入锁  非公平锁
    private ReentrantLock lock = new ReentrantLock();


    //测试 lock()获取锁  &  unlock()释放锁
    public void testLock(){
        //获取锁
        lock.lock();
        System.out.println(Thread.currentThread().getName()+"获得锁");
        try{
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+" i = "+i);
                try {
                    //sleep() 不会释放锁
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            //释放锁
            System.out.println(Thread.currentThread().getName()+"释放锁");
            lock.unlock();
        }
    }

    //测试 tryLock()尝试获取锁  &  unlock()释放锁
    public void testTryLock(){
        //尝试获取锁
        try {
            if (lock.tryLock(3,TimeUnit.SECONDS)) {
                System.out.println(Thread.currentThread().getName()+"获得锁");
                try{
                    for (int i = 0; i < 5; i++) {
                        System.out.println(Thread.currentThread().getName()+" i = "+i);
                        try {
                            //sleep() 不会释放锁
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }finally {
                    //释放锁
                    System.out.println(Thread.currentThread().getName()+"释放锁");
                    lock.unlock();
                }
            }else{
                System.out.println(Thread.currentThread().getName()+"未获得锁！");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {
        LockDemo demo = new LockDemo();

        /*new Thread(()->demo.testLock() , "T1").start();
        new Thread(()->demo.testLock() , "T2").start();*/

        new Thread(()->demo.testTryLock() , "T1").start();
        new Thread(()->demo.testTryLock() , "T2").start();
    }

}
